<template>
  <div class="zy-content">
    <div class="planAddWrapper">
      <div class="operateGroup">
        <h1 v-if="planId">编辑生产计划</h1>
        <h1 v-else>新建生产计划</h1>
        <div>
          <Button type="primary" v-show="!viewOnly" @click="save('onlySave')">{{planId ? "修改" : "保存"}}</Button>
          <Button type="primary" v-show="!viewOnly" @click="save('saveAndAdd')" v-if="!planId">保存并新建</Button>
          <Button @click="goBack">返回</Button>
        </div>
      </div>
      <Form :disabled="viewOnly"  ref="formValidate"  class="formList pd16" :model="formItem" label-position="top" :rules="ruleValidate">
        <Row :gutter="20">
          <Col span="8" :xxl="6">
            <FormItem label="车间产线" prop="productionLineId">
              <Cascader clearable :data="orgList" v-model="formItem.productionLineId" placeholder="请选择" change-on-select @on-change="orgListChange"></Cascader>
            </FormItem>
          </Col>
          <Col span="8" :xxl="6">
            <FormItem label="计划类型" prop="planType">
              <Select v-model="formItem.planType" placeholder="请选择产线" :disabled="viewOnly">
                <Option :value="1">正常</Option>
                <Option :value="2">返工</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8" :xxl="6">
            <FormItem label="生产计划类型" prop="productionType">
              <Select v-model="formItem.productionType" placeholder="请选择生产计划类型">
                <Option :value="1">面向销售订单</Option>
                <Option :value="2">面向库存</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="8"  :xxl="6">
            <FormItem label="生产计划号" prop="planNo">
              <Input disabled v-model="formItem.planNo"/>
            </FormItem>
          </Col>
          <Col span="8" :xxl="6">
            <FormItem label="同计划卡控" prop="samePlanCardControl">
              <Select v-model="formItem.samePlanCardControl" placeholder="请选择生产计划类型">
                <Option :value="1">是</Option>
                <Option :value="0">否</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="" prop="directDistribution">
              <Checkbox v-model="formItem.directDistribution">直接下发</Checkbox>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="备注" prop="memo">
              <Input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 3 }"
                  v-model="formItem.memo"
                  placeholder="当前字数限制200"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <!-- 产出物料 -->
      <Tabs value="name1" class="tabsWrapper">
        <TabPane label="产出物料" name="name1">
          <Table
              class="resizable-table"
              border
              size="small"
              @on-column-width-resize="onColumnWidthResize"
              :columns="columns"
              ellipsis
              stripe
              :data="dataArr"
          >
            <template #materialCode="{ row, index }">
              <Poptip placement="top" trigger="click" :transfer="true">
                <Input class="alignCenter" type="text" :disabled="viewOnly" readonly v-model="dataArr[index].materialCode" :placeholder="`${dataArr[index].materialCode}` || '请选择'"/>
                <template #content>
                  <materialSelect @change="selectProduct(index, $event)"/>
                </template>
              </Poptip>
            </template>
            <template #materialQty="{ row, index }">
              <InputNumber class="alignCenter" :min="0" @on-change="materialQtyChange"  v-model="dataArr[index].materialQty" :disabled="viewOnly"/>
            </template>
            <template #startTime="{ row, index }">
              <DatePicker v-model="dataArr[index].startTime" :disabled="viewOnly" @on-change="changTime($event, 'startTime')" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择时间" :transfer="true"/>
            </template>
            <template #endTime="{ row, index }">
              <DatePicker v-model="dataArr[index].endTime" :disabled="viewOnly" @on-change="changTime($event, 'endTime')" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择时间" :transfer="true"/>
            </template>
            <template #bomId="{ row, index }">
              <RollingLoadSelect :label-in-value="true" v-model="dataArr[index].bomId" @scrollBottom="bomScrollBottom" :disabled="viewOnly" @on-change="selectBom($event, index )" @on-open-change="bomSelectOpen" :clearable="true" @on-clear="getBomVersion">
                <Option v-for="item in bomVersionList" :value="item.id" :key="item.id" :label="item.version"></Option>
              </RollingLoadSelect>
            </template>
            <template #customerId="{ row, index }">
              <RollingLoadSelect :label-in-value="true" v-model="dataArr[index].customerId" :clearable="true" :filterable="true" :disabled="viewOnly" @scrollBottom="customerScrollBottom" @on-change="selectCustomer($event, index )" @on-query-change="getCustomerList">
                <Option v-for="item in cusList" :value="item.id" :key="item.id" :label="item.customerName">{{item.id}} - {{item.customerName}}</Option>
              </RollingLoadSelect>
            </template>
            <template #materialEdition="{ row, index }">
              <Input class="alignCenter" type="text" v-model="dataArr[index].materialEdition" :disabled="viewOnly" :placeholder="`${dataArr[index].materialEdition}`" />
            </template>
            <template #snp="{ row, index }">
              <Input class="alignCenter" type="text" v-model="dataArr[index].snp" :disabled="viewOnly" :placeholder="`${dataArr[index].snp}`" />
            </template>
            <template #batchNo="{ row, index }">
              <Input class="alignCenter" type="text" v-model="dataArr[index].batchNo" :disabled="viewOnly" :placeholder="`${dataArr[index].batchNo}`" />
            </template>
            <template #memo="{ row, index }">
              <Input class="alignCenter" type="text" v-model="dataArr[index].memo" :disabled="viewOnly" :placeholder="`${dataArr[index].memo}`"/>
            </template>
          </Table>
        </TabPane>
      </Tabs>
      <!--工序创建-->
      <div class="processCreation">
        <simple-draw
            :canvasData="canvasData"
            ref="simpleDraw"
            @create="
                  (param, callback) => {
                    createCore(param, callback);
                  }
                "
            @delete="
                  (param, callback) => {
                    deleteCore(param, callback);
                  }
                "
            @click="clickCore"
            :edit="false"
            style="width: 100%; height: 250px"
        />
        <div v-for="item in routeList" :key="item.position">
          <template v-if="item.position === currentRouteId">
            <div class="processTemplate">
              <Form  class="formList pd16" label-position="right" :label-width="150">
                <Row :gutter="20">
                  <Col span="8" :xxl="6">
                    <FormItem label="序号">
                      <InputNumber :disabled="true" class="inputCont" v-model="item.seq" placeholder="请输入序号"/>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="工序">
                      <RollingLoadSelect :disabled="true" :label-in-value="true" v-model="item.procId" @scrollBottom="procedureScrollBottom" @on-change="selectProcedure" placeholder="请选择">
                        <Option v-for="val in procedureData" :value="val.id" :key="val.id">{{val.procedureName}}</Option>
                      </RollingLoadSelect>
                    </FormItem>
                  </Col>
                  <!-- <Col span="8" :xxl="6">
                    <FormItem label="单次扫码">
                      <div v-if="item.singleBarcodeScanName === 1" style="border: 1px solid #dcdee2;padding: 0 7px;">是</div>
                      <div v-else style="border: 1px solid #dcdee2;padding: 0 7px;">否</div>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="一码到底">
                      <div v-if="item.barcodeToEndName === 1" style="border: 1px solid #dcdee2;padding: 0 7px;">是</div>
                      <div v-else style="border: 1px solid #dcdee2;padding: 0 7px;">否</div>
                    </FormItem>
                  </Col> -->
                  <Col span="8" :xxl="6">
                    <FormItem label="时间单位">
                      <Select :disabled="true" v-model="item.timeUnit" placeholder="请选择">
                        <Option :value="1">秒</Option>
                        <Option :value="2">分钟</Option>
                        <Option :value="3">小时</Option>
                        <Option :value="4">天</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="加工时间">
                      <InputNumber :disabled="true" class="inputCont" v-model="item.machiningTime" placeholder="请输入"  />
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="准备时间">
                      <InputNumber :disabled="true" class="inputCont" v-model="item.prepareTime" placeholder="请输入"  />
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="SNP">
                      <InputNumber :disabled="true" class="inputCont" v-model="item.snp" placeholder="请输入"  />
                    </FormItem>
                  </Col>
                  <!-- <Col span="8" :xxl="6">
                    <FormItem label="首件检验">
                      <Select :disabled="true" v-model="item.firstInspection" placeholder="请选择">
                        <Option :value="1">是</Option>
                        <Option :value="0">否</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="末件检验">
                      <Select :disabled="true" v-model="item.finalInspection" placeholder="请选择">
                        <Option :value="1">是</Option>
                        <Option :value="0">否</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="报工顺序控制">
                      <Select :disabled="true" v-model="item.sequenceControl" placeholder="请选择">
                        <Option :value="1">不控制</Option>
                        <Option :value="2">严格控制</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="报工数量控制(任务)">
                      <Select :disabled="true" v-model="item.quantityControl" placeholder="请选择">
                        <Option :value="1">不控制</Option>
                        <Option :value="2">严格控制</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="报工数量控制(交接)">
                      <Select :disabled="true" v-model="item.handoverControl" placeholder="请选择">
                        <Option :value="1">不控制</Option>
                        <Option :value="2">严格控制</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="报工工装控制">
                      <Select :disabled="true" v-model="item.toolingControl" placeholder="请选择">
                        <Option :value="1">不控制</Option>
                        <Option :value="2">严格控制</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="报工转码控制">
                      <Select :disabled="true" v-model="item.transcodingControl" placeholder="请选择">
                        <Option :value="1">不控制</Option>
                        <Option :value="2">严格控制</Option>
                      </Select>
                    </FormItem>
                  </Col> -->
                  <Col span="8" :xxl="6">
                    <FormItem label="物料转移类型">
                      <Select :disabled="true" v-model="item.materialTransfer" placeholder="请选择">
                        <Option :value="1">自动入库</Option>
                        <Option :value="2">生成入库任务</Option>
                        <Option :value="3">手动交接</Option>
                        <Option :value="4">自动交接</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="入库仓库">
                      <Select :disabled="true" v-model="item.warehouseId" placeholder="请选择">
                        <Option v-for="val in backUpData" :value="val.id" :key="val.id">{{val.companyName}}</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <!-- <Col span="8" :xxl="6">
                    <FormItem label="工序报工审核">
                      <Select :disabled="true" v-model="item.reportVerification" placeholder="请选择">
                        <Option :value="1">是</Option>
                        <Option :value="0">否</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8" :xxl="6">
                    <FormItem label="工序产出比例">
                      <InputNumber :disabled="true" class="inputCont" v-model="item.processOutputRatio" placeholder="请输入"  />
                    </FormItem>
                  </Col> -->
                  <Col span="8" :xxl="6">
                    <FormItem label="计划良率(%)">
                      <InputNumber class="inputCont" :min="0" v-model="item.planYield" placeholder="请输入"  />
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="生产描述">
                      <Input
                          :disabled="true"
                          type="textarea"
                          :autosize="{ minRows: 3, maxRows: 3 }"
                          v-model="item.memo"
                          placeholder="当前字数限制200"
                      />
                    </FormItem>
                  </Col>
                  <!-- <Col span="24">
                    <FormItem label="图纸附件" prop="uploadAttachment">
                      <div>{{item.uploadAttachment}}</div>
                    </FormItem>
                  </Col> -->
                </Row>
              </Form>
            </div>
            <div class="setMaterial">
              <Tabs v-model="materialTab" class="tabsWrapper" type="card">
                <TabPane label="投入物料" name="inputMaterials">
                  <Table
                      class="resizable-table"
                      border
                      size="small"
                      @on-column-width-resize="onColumnWidthResize"
                      :columns="materialColumns"
                      ellipsis
                      stripe
                      :data="item.tableData1"
                      @on-row-dblclick="clickMaterialRow"
                  >
                    <template #materialCode="{ row, index }">
                      <Poptip placement="top" trigger="click" :transfer="true">
                        <Input class="alignCenter" type="text" :disabled="true" v-model="item.tableData1[index].materialCode" :placeholder="row.materialCode"/>
                        <template #content>
                          <materialSelect @change="selectMaterial(item.tableData1, index, $event)"/>
                        </template>
                      </Poptip>
                    </template>
                    <template #calculateQty="{ row, index }">
                      <InputNumber class="alignCenter" :disabled="true" :value="row.calculateQty"/>
                    </template>
                    <template #lossRate="{ row, index }">
                      <InputNumber class="alignCenter" :disabled="true" v-model="item.tableData1[index].lossRate"/>
                    </template>
                    <template #inputMaterialControl="{ row, index }">
                      <Select v-model="item.tableData1[index].inputMaterialControl" :transfer="true" :disabled="true">
                        <Option :value="1">是</Option>
                        <Option :value="2">否</Option>
                      </Select>
                    </template>
                    <template #memo="{ row, index }">
                      <Input class="alignCenter" type="text" :disabled="true" v-model="item.tableData1[index].memo" placeholder="请输入备注"/>
                    </template>
                    <template #action="{ row, index }">
                      <Button type="error" size="small" :disabled="true" @click="removeMaterialRow(item,  index)">删除</Button>
                    </template>
                  </Table>
                </TabPane>
                <TabPane label="产出物料" name="outputMaterials">
                  <Table
                      class="resizable-table"
                      border
                      size="small"
                      @on-column-width-resize="onColumnWidthResize"
                      :columns="materialColumns"
                      ellipsis
                      stripe
                      :data="item.tableData2"
                      @on-row-dblclick="clickMaterialRow"
                  >
                    <template #materialCode="{ row, index }">
                      <Poptip placement="top" trigger="click" :transfer="true">
                        <Input class="alignCenter" type="text" :disabled="true" v-model="item.tableData2[index].materialCode" :placeholder="item.tableData2[index].materialCode"/>
                        <template #content>
                          <materialSelect @change="selectMaterial(item.tableData2, index, $event)"/>
                        </template>
                      </Poptip>
                    </template>
                    <template #calculateQty="{ row, index }">
                      <InputNumber class="alignCenter" :disabled="true" :value="row.calculateQty"/>
                    </template>
                    <template #lossRate="{ row, index }">
                      <InputNumber class="alignCenter" :disabled="true" v-model="item.tableData2[index].lossRate"/>
                    </template>
                    <template #inputMaterialControl="{ row, index }">
                      <Select v-model="item.tableData2[index].inputMaterialControl" :transfer="true" :disabled="true">
                        <Option :value="1">是</Option>
                        <Option :value="2">否</Option>
                      </Select>
                    </template>
                    <template #memo="{ row, index }">
                      <Input class="alignCenter" type="text" :disabled="true" v-model="item.tableData2[index].memo" placeholder="请输入备注"/>
                    </template>
                    <template #action="{ row, index }">
                      <Button type="error" size="small" :disabled="true" @click="removeMaterialRow(item,  index)">删除</Button>
                    </template>
                  </Table>
                </TabPane>
              </Tabs>
<!--              <div v-show="!viewOnly && !planId">-->
<!--                <Button class="addBtn" type="text" ghost size="small" @click="addMaterialRow(item)">+  添加一行</Button>-->
<!--              </div>-->
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
    addPlan,
    bomInfo,
    customerList,
    findOrgByToken,
    planInfo,
    procedureList,
    queryBackups,
    updatePlan,
    versionList
} from "@/api/planManage/productionPlan";
import SimpleDraw from "@/components/SimpleDraw/index.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from "@/util/recursion";
import moment from 'moment';
import materialSelect from './modules/materialSelect.vue';
import RollingLoadSelect from './modules/RollingLoadSelect.vue';
export default {
  name: "productionPlanAdd",
  mixins: [toggleTableOperation],
  components: {materialSelect, SimpleDraw, RollingLoadSelect},
  data() {
    return{
      planId: this.$route.query.id,
      formItem: {
        productionLineId: [],
        directDistribution: false,
        samePlanCardControl: '',
        productionType: '',
        planType: '',
        planNo: '',
        memo: ''
      },
      ruleValidate: {
        productionLineId: [{required: true, type: 'array', message: '请选择车间产线'}],
        planType: [{required: true, message: '请选择计划类型'}],
        productionType: [{required: true, message: '请选择生产计划类型'}],
      },
      columns: [
        {
          title: "序号",
          type: 'index',
          width: 80,
          align: 'center'
        },
        {
          title: "产品编号",
          key: "materialCode",
          minWidth: 250,
          slot: 'materialCode',
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "产品名称",
          key: "materialName",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "数量",
          key: "materialQty",
          slot: "materialQty",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "开始时间",
          key: "startTime",
          slot: "startTime",
          minWidth: 180,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "结束时间",
          key: "endTime",
          slot: "endTime",
          minWidth: 180,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "BOM版本号",
          key: "bomId",
          slot: "bomId",
          width: 160,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "转换率",
          key: "unitConversionRate",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "客户",
          key: "customerId",
          slot: "customerId",
          width: 160,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "次单位",
          key: "tmSubunitsName",
          width: 100,
          align: "center",
        },
        {
          title: "物料版本",
          key: "materialEdition",
          slot: "materialEdition",
          width: 100,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "单位",
          key: "tmUnitName",
          width: 100,
          align: "center",
        },
        {
          title: "SNP",
          key: "snp",
          slot: "snp",
          width: 160,
          align: "center",
        },
        {
          title: "物料清单代替项",
          key: "alternateMaterialName",
          width: 160,
          align: "center",
        },
        {
          title: "BOM图纸附件",
          key: "bomDrawing",
          width: 180,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "生产批号",
          key: "batchNo",
          slot: "batchNo",
          width: 160,
          align: "center",
        },
        {
          title: "备注",
          key: "memo",
          slot: "memo",
          width: 160,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "创建人",
          key: "crtUsrName",
          width: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "创建时间",
          key: "crtTime",
          width: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "更新人",
          key: "updUsrName",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: "更新时间",
          key: "updTime",
          minWidth: 170,
          align: "center",
          resizable: true,
          tooltip: true,
        }
      ],
      dataArr: [
        {
          materialCode: '',
          materialName: '',
          materialQty: 0,
          bomId: '',
          unitConversionRate: '',
          customerId: '',
          tmSubunitsName: '',
          materialEdition: '',
          tmUnitName: '',
          snp: '',
          alternateMaterialName: '',
          bomDrawing: '',
          batchNo: '',
          memo: '',
          startTime: '',
          endTime: '',
          crtUsrName: '',
          crtTime: '',
          updUsrName: '',
          updTime: ''
        }
      ],
      bomVersionList: [],
      bomVersionParams: {
        pageNum: 1,
        pages: 0,
        materialId: ''
      },
      cusList: [],
      customParams: {
        pageNum: 1,
        customerName: '',
        pages: 0,
      },
      canvasData: {},
      routeList: [],
      currentRouteId: '',
      materialTab: 'inputMaterials',
      materialColumns: [
        {
          title: "序号",
          type: 'index',
          width: 80,
          align: 'center'
        },
        {
          title: "物料编号",
          slot: "materialCode",
          key: "materialCode",
          minWidth: 160,
          align: "center",
          resizable: true
        },
        {
          title: "物料名称",
          key: "materialName",
          minWidth: 160,
          align: "center",
          resizable: true
        },
        {
          title: "数量",
          slot: "calculateQty",
          key: "calculateQty",
          minWidth: 130,
          align: "center",
          resizable: true
        },
        {
          title: "单位",
          key: "tmUnitName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "次单位",
          key: "tmSubunitsName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "转换率",
          key: "unitConversionRate",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "物料属性",
          key: "materialPropertiesName",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: "损耗率(%)",
          slot: "lossRate",
          key: "lossRate",
          minWidth: 130,
          align: "center",
          resizable: true
        },
        {
          title: "是否管控",
          slot: "inputMaterialControl",
          key: "inputMaterialControl",
          minWidth: 160,
          align: "center",
          resizable: true
        },
        {
          title: "备注",
          slot: "memo",
          key: "memo",
          minWidth: 160,
          align: "center",
          resizable: true
        },
        {
          title: "预定义1",
          key: "predefine1",
          minWidth: 160,
          align: "center",
          resizable: true,
        },
        {
          title: "预定义2",
          key: "predefine2",
          minWidth: 160,
          align: "center",
          resizable: true
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 100,
          align: "center"
        }
      ],
      selectMaterialRow: {},
      viewOnly: false,
      seq: 0,
      procedureData: [],
      procedureParams: {
        pageNum: 1,
        pages: 0,
      },
      backUpData:[],
      orgList:[],
    }
  },
  created() {
    if(this.planId){
      this.getPlanInfo();
    } else {
      this.getOrgList();
      this.getCustomerList();
    }
    this.getProcedureList();
    this.getQueryBackups();
  },
  mounted() {
    if(this.viewOnly){
      this.columns.splice(this.columns.length - 1, 1);
      this.materialColumns.splice(this.materialColumns.length - 1, 1);
    }

  },
  methods: {
    goBack () {
      this.$router.push('/planManage/productionPlan')
    },
    materialQtyChange(materialQty){
      for (let i = 0; i < this.routeList.length; i++) {
        const element=this.routeList[i];
        for (let j = 0; j < element.tableData1.length; j++) {
          this.$set(this.routeList[i].tableData1[j],'calculateQty',(materialQty || 1)*element.tableData1[j].materialQty)
        }
        for (let j = 0; j < element.tableData2.length; j++) {
          this.$set(this.routeList[i].tableData2[j],'calculateQty',(materialQty || 1)*element.tableData2[j].materialQty)
        }
      }
    },
    changTime(value, type){
      if(type === 'startTime'){
        this.dataArr[0].startTime = value
      } else {
        this.dataArr[0].endTime = value
      }
    },
    getOrgList(productionLineId) {
      findOrgByToken({level: 0}).then(res => {
        if (res.code === 200) {
          const obj = {
            label: "name",
            value: "id",
            children: "children"
          };
          this.orgList = recursion.convertTree(res.data, obj);
          if(productionLineId){
            let factoryId = [];
            for (let i = 0; i < this.orgList.length; i++) {
              if (productionLineId === this.orgList[i].id) {
                factoryId = [this.orgList[i].id];
                break;
              }
              if(this.orgList[i].children){
                for (let j = 0; j < this.orgList[i].children.length; j++) {
                  if (productionLineId === this.orgList[i].children[j].id) {
                    factoryId = [this.orgList[i].id, this.orgList[i].children[j].id];
                    break;
                  }
                  if(this.orgList[i].children[j].children){
                    for (let k = 0; k < this.orgList[i].children[j].children.length; k++) {
                      if (productionLineId === this.orgList[i].children[j].children[k].id) {
                        factoryId = [this.orgList[i].id, this.orgList[i].children[j].id, this.orgList[i].children[j].children[k].id];
                        break;
                      }
                    }
                  }
                }
              }
            }
            this.formItem.productionLineId = factoryId;
          } else {
            this.formItem.productionLineId = [];
          }
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    orgListChange(val, selectedData) {
      if (val.length > 0) {
        this.productionLineId = selectedData[selectedData.length - 1].id;
      } else {
        this.productionLineId = '';
      }
    },
    // 浮窗选择产品
    selectProduct(index, data) {
      this.$set(this.dataArr,0,{
        ...this.dataArr[0],
        bomId: '',
        label: '',
        bomDrawing: '',
        alternateMaterialName: '',
        ...data
      })
      this.canvasData = {};
      this.routeList = [];
      this.seq = 0;
      this.bomVersionParams = {
        materialId: data.id,
        pageNum: 1,
        pages: 0
      }
      this.dataArr.reverse().reverse();
      this.getBomVersion()
    },
    async getBomVersion(id){
      let params = {
        materialId: this.bomVersionParams.materialId,
        pageNum: this.bomVersionParams.pageNum,
        pageSize: 20
      }
      if(id){ // 编辑数据回显
        params.id = id;
      }
      const res= await versionList(params)
      if(res.code === 200){
        this.bomVersionList = res.data.list || [];
        this.bomVersionParams.pages = res.data.pages;
      } else {
        this.$Message.warning({content: res.msg})
      }
    },
    // bom下拉分页加载
    bomScrollBottom(callback){
      if(this.bomVersionParams.pageNum + 1 > this.bomVersionParams.pages){
        return callback(false)
      }
      this.bomVersionParams = {
        ...this.bomVersionParams,
        pageNum: this.bomVersionParams.pageNum + 1
      }
      versionList({
        materialId: this.bomVersionParams.materialId,
        pageNum: this.bomVersionParams.pageNum,
        pageSize: 20
      }).then(res => {
        if(res.code === 200){
          this.bomVersionList = this.bomVersionList.concat(res.data.list || []);
          this.bomVersionParams.pages = res.data.pages;
        } else {
          this.$Message.warning({content: res.msg})
        }
        callback(false)
      })
    },
    selectBom(info, index) {
      if(info){
        this.dataArr[index].bomId = info.value;
        this.dataArr[index].bomVersion = info.label;
        this.dataArr.reverse().reverse();
        this.getBomInfo(info, index)
      } else { // 选择取消 重置数据
        this.dataArr[index].bomId = '';
        this.dataArr[index].bomVersion = '';
        this.dataArr[index].bomDrawing = '';
        this.dataArr[index].alternateMaterialName = '';
        this.canvasData = {};
        this.seq = 0;
        this.routeList = [];
        this.dataArr.reverse().reverse();
      }
    },
    getBomInfo(info, index) {
      bomInfo({
        id: info.value
      }).then(res => {
        let {data = {} } = res || {};
        let bomInfo = data.bomInfo || {};
        this.dataArr[index].bomDrawing = bomInfo.bomDrawing;
        this.dataArr[index].alternateMaterialName = bomInfo.alternateMaterialName;
        this.canvasData = data.canvas || {};
        let seq = 0;
        if(data.routeList && data.routeList.length){
          const arr = [];
          data.routeList.forEach(item => {
            let obj = {
              ...item
            };
            seq = item.seq;
            let tableData1 = [], tableData2 =[];
            item.routeInOutputList && item.routeInOutputList.forEach(val => {
              const tranVal={
                ...val,
                calculateQty: val.materialQty*(this.dataArr[0].materialQty || 1)
              }
                if(val.inOutputFlag === 1){
                  tableData1.push(tranVal)
                } else {
                  tableData2.push(tranVal)
                }
            })
            delete obj.routeInOutputList;
            obj.tableData1 = tableData1;
            obj.tableData2 = tableData2;
            if(!obj.planYield){
              obj.planYield = 0 // 设置一个默认值
            }
            arr.push(obj)
          })
          this.routeList = arr;
        } else {
          this.routeList = [];
        }
        this.seq = seq;
        this.dataArr.reverse().reverse();
      })
    },
    bomSelectOpen(status){
      if(status){
        if(!this.bomVersionList.length && !this.dataArr[0].materialCode){
          this.$Message.warning({content: "请先选择产品"})
        }
      }
    },
    getCustomerList(query = ''){
      this.customParams.pageNum = 1;
      customerList({
        pageNum: this.customParams.pageNum,
        pageSize: 20,
        customerName: query
      }).then(res => {
        if(res.code === 200){
          let {data = []} = res || {};
          this.cusList = data.list || [];
          this.customParams.pages = data.pages || 0;
          this.customParams.customerName = query;
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    // 客户下拉分页加载
    customerScrollBottom(callback) {
      if(this.customParams.pageNum + 1 > this.customParams.pages){
        return callback(false)
      }
      this.customParams = {
        ...this.customParams,
        pageNum: this.customParams.pageNum + 1
      }
      customerList({
        pageNum: this.customParams.pageNum,
        pageSize: 20
      }).then(res => {
        if(res.code === 200){
          let {data = []} = res || {};
          this.cusList = this.cusList.concat(data.list || []);
          this.customParams.pages = data.pages || 0;
        } else {
          this.$Message.warning({content: res.msg})
        }
        callback(false)
      })
    },
    // 选择客户
    selectCustomer(info, index){
      if(info){
        this.dataArr[index].customerId = info.value;
        this.dataArr[index].customerName = info.label;
        this.cusList.reverse().reverse();
      } else {
        this.dataArr[index].customerId = '';
        this.dataArr[index].customerName = '';
        this.cusList.reverse().reverse();
      }
    },
    // 编辑工序
    createCore(param, callback){
      if(!this.dataArr[0].bomId && !this.dataArr[0].bomVersion){ // bomId 可能为0
        this.$Message.warning({content: '请先选择BOM版本'});
        return callback(false)
      }
      this.seq += 1;
      this.routeList.push({
        position: param.id,
        seq: this.seq, //序号
        procId: '', //工序ID
        timeUnit: 1, //时间单位(1秒 2分钟 3小时 4天)
        machiningTime: 0, //加工工时
        prepareTime: 0, //准备工时
        snp: 0, //最小经济批量
        firstInspection: 0, //首件检验1是 0否
        finalInspection: 0, //末件检验1是 0否
        sequenceControl: 1, //报工顺序控制 1不控制 2严格控制
        quantityControl: 1, //报工数量控制(任务)1不控制 2严格控制
        handoverControl: 1, //报工数量控制(交接)1不控制 2严格控制
        toolingControl: 1, //报工工装控制 1不控制 2严格控制
        transcodingControl: 1, //报工转码控制 1不控制 2严格控制
        reportVerification: 0, //工序报工审核 1是 0否
        materialTransfer: 1, //物料转移类型(1 自动入库 2 生成入库任务 3 手工交接 4 自动交接)
        warehouseId: '', //入库仓库
        processOutputRatio: 0, //工序产出比例
        uploadAttachment: "", //附件
        memo: "", //备注
        planYield: '', // 计划良率
        tableData1: [],
        tableData2: [],
      })
      callback(true)
    },
    deleteCore(param, callback){
      this.routeList = this.routeList.filter(val => val.position !== param.id);
      callback(true)
    },
    clickCore(param){
      this.currentRouteId = param.detail.id;
    },
    // 双击选中 产出物料
    clickMaterialRow(row) {
      if(this.viewOnly){
        return
      }
      this.selectMaterialRow = row;
    },
    // 添加一行
    addMaterialRow(itemInfo) {
      if(this.materialTab === 'inputMaterials'){ // 投入物料
        itemInfo.tableData1.push({
          inOutputFlag: 1, //投料/产出(1 投料,2产出)
          materialId: '',
          materialCode: '',
          materialName: '',
          quantity: 0,
          tmUnitName: '',
          tmSubunitsName: '',
          unitConversionRate: '',
          materialProperties: '',
          lossRate: 0,
          inputMaterialControl: '2',
          memo: '',
          predefine1: '',
          predefine2: '',
        })
      } else {
        itemInfo.tableData2.push({
          inOutputFlag: 2, //投料/产出(1 投料,2产出)
          materialId: '',
          materialCode: '',
          materialName: '',
          quantity: '',
          tmUnitName: '',
          tmSubunitsName: '',
          unitConversionRate: '',
          materialProperties: '',
          lossRate: '',
          inputMaterialControl: '',
          memo: '',
          predefine1: '',
          predefine2: '',
        })
      }
    },
    removeMaterialRow(itemInfo, index) {
      if(this.materialTab === 'inputMaterials') { // 投入物料
        itemInfo.tableData1.splice(index, 1)
      } else {
        itemInfo.tableData2.splice(index, 1)
      }
    },
    // 获取工序
    getProcedureList(){
      procedureList({
        pageNum: this.procedureParams.pageNum,
        pageSize: 20
      }).then(res => {
        if(res.code === 200){
          let {data = {} } = res || {};
          this.procedureData = data.list || [];
          this.procedureParams.pages = data.pages || 0;
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    // 工序滚动加载
    procedureScrollBottom(callback){
      if(this.procedureParams.pageNum + 1 > this.procedureParams.pages){
        return callback(false)
      }
      this.procedureParams = {
        ...this.procedureParams,
        pageNum: this.procedureParams.pageNum + 1
      }
      procedureList({
        pageNum: this.procedureParams.pageNum,
        pageSize: 20
      }).then(res => {
        if(res.code === 200){
          let {data = {} } = res || {};
          this.procedureData = this.procedureData.concat(data.list || []);
          this.procedureParams.pages = data.pages || 0;
        } else {
          this.$Message.warning({content: res.msg})
        }
        callback(false)
      })
    },
    // 选择工序
    selectProcedure(info){
      let item = this.procedureData.find(val => val.id === info.value);
      let parentItem = this.routeList.find(val => val.position === this.currentRouteId);
      parentItem.singleBarcodeScanName = item.singleBarcodeScan;
      parentItem.barcodeToEndName = item.barcodeToEnd;
      this.routeList.reverse().reverse(); // 更新
      this.$refs['simpleDraw'].changeCoreLabel(parentItem.position,item.procedureName);
    },
    // 仓库列表
    getQueryBackups(){
      queryBackups().then(res => {
        if(res.code === 200){
          this.backUpData = res.data || [];
        } else {
          this.$Message.warning({content: res.msg})
        }
      })
    },
    // 投入物料、产出物料选择物料
    selectMaterial(arr, index, info) {
      arr[index] = {
        materialId: info.id,
        materialCode: info.materialCode,
        materialName: info.materialName,
        materialQty: 0,
        tmUnitName: info.tmUnitName,
        tmSubunitsName: info.tmUnitName,
        unitConversionRate: info.unitConversionRate,
        materialProperties: info.materialProperties,
        lossRate: 0,
        inputMaterialControl: '2', //投料管控 1是 2否
        memo: info.memo,
        predefine1: info.predefine1,
        predefine2: info.predefine2,
      }
      this.materialColumns.reverse().reverse()
    },

    check(rules, obj) {
      return rules.some(val => {
        if(val.type === 'time' && (!obj[val.key] || obj[val.key] == 'Invalid date')){
          this.$Message.warning({content: val.tip});
          return true
        } else if(val.type === 'string' && !obj[val.key]){
          this.$Message.warning({content: val.tip});
          return true
        } else if(val.type === 'number' && (!obj[val.key] || obj[val.key] === 0)){
          this.$Message.warning({content: val.tip});
          return true
        }
        return false
      })
    },
    // 保存
    async save (type){
     let valid = await this.$refs.formValidate.validate();
      if(!valid) return;
      let params = {
        ...this.formItem,
        productionLineId: this.formItem.productionLineId[this.formItem.productionLineId.length - 1],
        directDistribution: this.formItem.directDistribution ? '1' : '0'
      }
      let planOut = {
        canvas: this.$refs.simpleDraw.getResult(),
        bomId: this.dataArr[0].bomId,
        materialQty: this.dataArr[0].materialQty,
        originalMaterialQty: this.dataArr[0].materialQty,  // 原始materialQty
        customerId: this.dataArr[0].customerId,
        materialEdition: this.dataArr[0].materialEdition,
        startTime: moment(this.dataArr[0].startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(this.dataArr[0].endTime).format('YYYY-MM-DD HH:mm:ss'),
        snp: this.dataArr[0].snp,
        batchNo: this.dataArr[0].batchNo,
        memo: this.dataArr[0].memo,
        routeList: [],
      }
      let keysCheck = [
        {key: 'startTime', type: 'time', tip: '请选择开始时间'},
        {key: 'endTime',  type: 'time', tip: '请选择结束时间'},
        {key: 'bomId',  type: 'number', tip: '请选择bom版本'},
        {key: 'materialQty',  type: 'number', tip: '请输入数量'},
        {key: 'customerId',  type: 'number', tip: '请选择客户'},
        {key: 'materialEdition',  type: 'string', tip: '请输入物料版本'},
        {key: 'snp',  type: 'string', tip: '请输入snp'},
        // {key: 'batchNo',  type: 'string', tip: '请输入批次号'}
      ]
      if(this.check(keysCheck, planOut)) return;
      let routeList = [];
      this.routeList.forEach(item => {
        let obj = {
            ...item,
          inoutPutInfo: []
        }
        item.tableData1.forEach(val => {
          obj.inoutPutInfo.push({
            materialId: val.materialId,
            inOutputFlag: 1,
            materialQty: val.materialQty,
            calculateQty: val.calculateQty,
            lossRate: val.lossRate,
            inputMaterialControl: val.inputMaterialControl,
            memo: val.memo
          })
        })
        item.tableData2.forEach(val => {
          obj.inoutPutInfo.push({
            materialId: val.materialId,
            inOutputFlag: 2,
            materialQty: val.materialQty,
            calculateQty: val.calculateQty,
            lossRate: val.lossRate,
            inputMaterialControl: val.inputMaterialControl,
            memo: val.memo
          })
        })
        delete obj.tableData1;
        delete obj.tableData2;
        routeList.push(obj)
      })
      if(routeList.length === 0){
        this.$Message.warning({content: '请添加工序'});
        return
      }

      planOut.routeList = routeList;
      params.planOut = planOut;

      if(this.$route.query.id){ // 编辑
        params.id = Number(this.planId);
        updatePlan(params).then(res => {
          if(res.code === 200){
            this.$Message.success({content: '修改成功'});
            setTimeout(() => {
              if(type === 'onlySave'){
                this.$router.push('/planManage/productionPlan')
              } else {
                this.$router.go(0)
              }
            }, 2000)
          } else {
            this.$Message.warning({content: res.msg});
          }
        })
      } else {
        addPlan(params).then(res => {
          if(res.code === 200){
            this.$Message.success({content: '新建成功'});
            setTimeout(() => {
              if(type === 'onlySave'){
                this.$router.push('/planManage/productionPlan')
              } else {
                this.$router.go(0)
              }
            }, 2000)
          } else {
            this.$Message.warning({content: res.msg});
          }
        })
      }

    },
    async getPlanInfo(){
      const res=await planInfo({id: this.$route.query.id })
      if(res.code === 200){
        let { data = {} } = res || {};
        if(data.planInfo){
            this.bomVersionParams = {
            materialId: data.planInfo.planOut.materialId,
            pageNum: 1,
            pages: 0
          }
          await this.getBomVersion(data.planInfo.planOut.bomId);
          this.formItem = {
            productionLineId: [],
            directDistribution: !!data.planInfo.directDistribution,
            samePlanCardControl: data.planInfo.samePlanCardControl,
            productionType: data.planInfo.productionType,
            planType: data.planInfo.planType,
            memo: data.planInfo.memo,
            planNo: data.planInfo.planNo
          }
          this.getOrgList(data.planInfo.productionLineId);
          this.getCustomerList(data.planInfo.planOut.customerName);
          this.dataArr[0] = {
            ...data.planInfo.planOut,
            tmUnitName: data.planInfo.planOut.unitName,
            tmSubunitsName: data.planInfo.planOut.subunitsName
          };
          this.dataArr.reverse().reverse();

          if(data.planInfo.planStatus !== 0){
            this.viewOnly = true
          }
        }

        let seq = 0;
        if(data.routeList && data.routeList.length){
          const arr = [];
          data.routeList.forEach(item => {
            let obj = {
              ...item
            };
            seq = item.seq;
            let tableData1 = [], tableData2 =[];
            item.inoutPutInfo && item.inoutPutInfo.forEach(val => {
              if(!val.calculateQty){
                val.calculateQty = 0 // 设置一个默认值
              }
              if(val.inOutputFlag === 1){
                tableData1.push(val)
              } else {
                tableData2.push(val)
              }
            })
            delete obj.inoutPutInfo;
            obj.tableData1 = tableData1;
            obj.tableData2 = tableData2;
            if(!obj.planYield){
              obj.planYield = 0 // 设置一个默认值
            }
            arr.push(obj)
          })
          this.routeList = arr;
        }
        this.seq = seq;
        this.dataArr.reverse().reverse();
        this.canvasData = data.canvas || {};
      } else {
        this.$Message.warning({content: res.msg})
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.planAddWrapper{
  background: #ffffff;
  .operateGroup{
   padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    h1{
      font-weight: bolder;
      font-size: 18px;
    }
    button{
      margin-left: 20px;
    }
  }
  :deep(.ivu-input.ivu-input-disabled){
    background-color: #f3f3f3 !important;
    color: #ccc;
  }
  :deep(.ivu-select-disabled){
    background-color: #f3f3f3 !important;
    color: #ccc;
  }
  :deep(.ivu-input-number-disabled .ivu-input-number-input){
    background-color: #f3f3f3 !important;
    color: #ccc;
  }
  .tabsWrapper{
    padding: 15px 20px;
    .filterData{
      display: flex;
      padding: 15px 25px;
      align-items: center;
      .input{
        width: 350px;
        margin-left: 15px;
      }
    }
    .alignCenter{
      text-align: center;
      :deep(input){
        text-align: center;
      }
    }
    :deep(.filterActiveItem){
      background: #85a039;
      td{
        background: #85a039;
      }
    }
  }
  .addBtn{
    color: rgb(24, 144, 255);
    border: none;
    margin: 15px 0 ;
  }
  .processCreation{
    padding: 15px 20px;
    .processTemplate{
      background-color: #f7f7f7;
      padding: 10px;
      border: 1px solid #ededed;
      margin-top: 20px;
      .inputCont{
        width: 100%;
      }
    }
    .setMaterial{
      .tabsWrapper{
        background: #e3e8ee;
        padding:16px;
      }
      :deep(.ivu-tabs-tabpane){
        padding-top: 20px;
        background: #ffffff;
      }
    }
  }
}
</style>

<style lang="scss">
.selectList{
  display: block;
  .item{
    display: block;
    padding: 8px 15px;
    cursor: pointer;
    max-width: 540px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    &:hover{
      background: #f8f8f9;
    }
  }
}
</style>
